package com.hikvision.open.app.ui.playback

import android.Manifest
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.hikvision.hatomplayer.core.PlaybackSpeed
import com.hikvision.open.app.model.PlayStatus
import com.hikvision.open.app.ui.preview.PlayWindowView
import com.hikvision.open.app.utils.CalendarUtil
import com.hikvision.open.app.utils.MyUtils
import com.hikvision.open.app.utils.PermissionHelper
import com.hikvision.open.app.widget.PermissionDialog
import com.hikvision.open.app.widget.window.WindowGroupAdapter
import hik.sdk.demo.R
import hik.sdk.demo.databinding.ViewPlaybackControlBinding

/**
 * <p> 回放控制View </p>
 * @author 段自航 2021/7/15 15:27
 * @version V1.0
 */
class PlaybackControlView : ConstraintLayout, View.OnClickListener {

    private lateinit var viewBinding: ViewPlaybackControlBinding

    private var windowGroupHelper: WindowGroupAdapter? = null

    private var playbackUrl =
        "rtsp://124.225.17.33:554/openUrl/rZxMCSA?beginTime=20240226T000000&endTime=20240226T150944&playBackMode=1"

    private var startTime: Long = 0L
    private var endTime: Long = 0L

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initView()
    }

    private fun initView() {
        setBackgroundResource(R.color.white)
        viewBinding = ViewPlaybackControlBinding.inflate(LayoutInflater.from(context), this)
        viewBinding.playbackUrlEdit.setText(playbackUrl)
        //设置功能按钮点击监听
        viewBinding.openHardDecodeButton.setOnClickListener(this)
        viewBinding.closeHardDecodeButton.setOnClickListener(this)
        viewBinding.openSmartButton.setOnClickListener(this)
        viewBinding.closeSmartButton.setOnClickListener(this)
        viewBinding.startPlaybackButton.setOnClickListener(this)
        viewBinding.stopPlaybackButton.setOnClickListener(this)
        viewBinding.pauseButton.setOnClickListener(this)
        viewBinding.resumeButton.setOnClickListener(this)
        viewBinding.openSoundButton.setOnClickListener(this)
        viewBinding.closeSoundButton.setOnClickListener(this)
        viewBinding.captureButton.setOnClickListener(this)
        viewBinding.startRecordButton.setOnClickListener(this)
        viewBinding.stopRecordButton.setOnClickListener(this)
        viewBinding.speedOneButton.setOnClickListener(this)
        viewBinding.speedTwoButton.setOnClickListener(this)
        viewBinding.speedFourButton.setOnClickListener(this)
        viewBinding.speedEightButton.setOnClickListener(this)
        //显示当天默认起止时间
        val defaultStartCalendar = CalendarUtil.getDefaultStartCalendar()
        startTime = defaultStartCalendar.timeInMillis
        val curDayEndTime = CalendarUtil.getCurDayEndTime(startTime)
        endTime = curDayEndTime
    }

    fun setWindowGroupHelper(windowGroupAdapter: WindowGroupAdapter) {
        this.windowGroupHelper = windowGroupAdapter
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.openHardDecodeButton -> {
                setHardDecode(true)
            }

            R.id.closeHardDecodeButton -> {
                setHardDecode(false)
            }

            R.id.openSmartButton -> {
                setSmartDetect(true)
            }

            R.id.closeSmartButton -> {
                setSmartDetect(false)
            }

            R.id.startPlaybackButton -> {
                startPlayback()
            }

            R.id.stopPlaybackButton -> {
                stopPlayback()
            }

            R.id.pauseButton -> {
                pause()
            }

            R.id.resumeButton -> {
                resume()
            }

            R.id.openSoundButton -> {
                openSound()
            }

            R.id.closeSoundButton -> {
                closeSound()
            }

            R.id.captureButton -> {
                capture()
            }

            R.id.startRecordButton -> {
                startRecord()
            }

            R.id.stopRecordButton -> {
                stopRecord()
            }

            R.id.speedOneButton -> {
                setSpeed(PlaybackSpeed.NORMAL)
            }

            R.id.speedTwoButton -> {
                setSpeed(PlaybackSpeed.DOUBLE)
            }

            R.id.speedFourButton -> {
                setSpeed(PlaybackSpeed.FOUR)
            }

            R.id.speedEightButton -> {
                setSpeed(PlaybackSpeed.EIGHT)
            }

            else -> {
            }
        }
    }


    /**
     * 设置硬解码
     */
    private fun setHardDecode(isHardDecode: Boolean) {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() == PlayStatus.PLAYING) {
                Toast.makeText(context, "请在播放之前设置", Toast.LENGTH_SHORT).show()
                return@let
            }
            playWindowView.setHardDecodePlay(isHardDecode)
            val content = if (isHardDecode) "硬解码开" else "硬解码关"
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 设置智能信息
     */
    private fun setSmartDetect(isSmartDetect: Boolean) {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() == PlayStatus.PLAYING) {
                Toast.makeText(context, "请在播放之前设置", Toast.LENGTH_SHORT).show()
                return@let
            }
            playWindowView.setSmartDetect(isSmartDetect)
            val content = if (isSmartDetect) "智能信息开" else "智能信息关"
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show()

        }
    }

    /**
     * 开启回放
     */
    private fun startPlayback() {
        windowGroupHelper?.currentWindowItem?.let {
            val url = viewBinding.playbackUrlEdit.text.toString()
            if (url.isEmpty()) {
                Toast.makeText(context, "请输入回放Url", Toast.LENGTH_SHORT).show()
                return@let
            }
            val playWindowView = it as PlayWindowView
            //默认了起止时间是当天
            playWindowView.startPlay(url, startTime, endTime)
        }
    }

    /**
     * 关闭回放
     */
    private fun stopPlayback() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            playWindowView.stopPlay()
            playWindowView.showPlayIdle()
        }
    }

    /**
     * 暂停
     */
    private fun pause() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (!playWindowView.isPause) {
                playWindowView.executePauseOrResume()
            }
        }
    }

    /**
     * 恢复
     */
    private fun resume() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (playWindowView.isPause) {
                playWindowView.executePauseOrResume()
            }
        }
    }


    /**
     * 开启声音
     */
    private fun openSound() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (playWindowView.isPause) {
                Toast.makeText(context, "视频已暂停", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (!playWindowView.isOpenAudio) {
                playWindowView.executeSound()
                Toast.makeText(context, "声音已打开", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 关闭声音
     */
    private fun closeSound() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (playWindowView.isOpenAudio) {
                playWindowView.executeSound()
                Toast.makeText(context, "声音已关闭", Toast.LENGTH_SHORT).show()
            }
        }
    }


    /**
     * 抓拍
     */
    private fun capture() {
        //进行权限判断
        if (PermissionHelper.isGranted(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            doCapture()
        } else {

            Toast.makeText(context, "没有权限", Toast.LENGTH_SHORT).show();

            //请求权限
            val activity = MyUtils.getActivity(this) as? FragmentActivity ?: return
            PermissionHelper.requestStoragePermission(activity) { allGranted ->
                if (allGranted) {
                    doCapture()
                }
            }
        }
    }

    private fun doCapture() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            playWindowView.executeCapture()
            Toast.makeText(context, "抓图成功", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 开启录像
     */
    private fun startRecord() {
        //进行权限判断
        if (PermissionHelper.isGranted(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            doStartRecord()
        } else {
            //请求权限
            val activity = MyUtils.getActivity(this) as? FragmentActivity ?: return
            PermissionHelper.requestStoragePermission(activity) { allGranted ->
                if (allGranted) {
                    doStartRecord()
                }
            }
        }
    }

    private fun doStartRecord() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (playWindowView.isPause) {
                Toast.makeText(context, "视频已暂停", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (!playWindowView.isRecording) {
                val recordPath = playWindowView.executeRecord()
                Toast.makeText(context, "开始录像", Toast.LENGTH_SHORT).show()
                viewBinding.recordPathText.text = recordPath
            }
        }
    }

    /**
     * 关闭录像
     */
    private fun stopRecord() {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            if (playWindowView.isRecording) {
                playWindowView.executeRecord()
                Toast.makeText(context, "关闭录像", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 设置回放速度
     */
    private fun setSpeed(speed: PlaybackSpeed) {
        windowGroupHelper?.currentWindowItem?.let {
            val playWindowView = it as PlayWindowView
            if (playWindowView.getPlayStatus() != PlayStatus.PLAYING) {
                Toast.makeText(context, "没有视频在播放", Toast.LENGTH_SHORT).show()
                return@let
            }
            val content = when (speed) {
                PlaybackSpeed.NORMAL -> "1倍速"
                PlaybackSpeed.DOUBLE -> "2倍速"
                PlaybackSpeed.FOUR -> "4倍速"
                PlaybackSpeed.EIGHT -> "8倍速"
                else -> "1倍速"
            }
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show()
            playWindowView.setPlaybackSpeed(speed)
        }
    }
}